package com.itheima.stock.remotedata;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.stock.job.service.StockTimerService;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockRtInfo;
import com.itheima.stock.utils.IdWorker;
import com.itheima.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.math.BigDecimal;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@SpringBootTest
public class PullRemoteData1 {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private StockTimerService stockTimerService;
    @Test
    public void test1() throws ParseException {
        parseStockCodeData("600000");
    }

    /**
     * 拉取个股数据
     * @param code
     * @throws ParseException
     */
    public void parseStockCodeData(String code) throws ParseException {
        String host = "https://jsapigpcx.market.alicloudapi.com";
        String path = "/stock/query";
        String method = "GET";
        String appcode = "d47e8d73a72045b8b61a86764d7728ed";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("code", code);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            String geGuJson = EntityUtils.toString(response.getEntity());
            Map map = JSON.parseObject(geGuJson, Map.class);
            JSONArray jsonArray=(JSONArray) map.get("result");
            List<StockRtInfo> rtInfoList=new ArrayList<>();
            for (Object rt : jsonArray) {
                JSONObject jsonObj =  (JSONObject)rt;
                // 股票名称
                String name = jsonObj.get("name").toString();
                System.out.println("--------------"+name+"-------------");
                System.out.println("股票名称 "+name);
                String gpcode = jsonObj.get("code").toString();
                System.out.println("股票代码 "+gpcode);
               // String price=jsonObj.get("price").toString();
                BigDecimal price = new BigDecimal(jsonObj.get("price").toString());
                System.out.println("开盘价 "+price);
                BigDecimal lastclosingprice = new BigDecimal(jsonObj.get("lastclosingprice").toString());
                System.out.println("前收盘价"+lastclosingprice);
                // 当前日期
               // Date updatetime = new DateTime(Long.parseLong(jsonObj.get("updatetime") + "000")).toDate();
                String updatetime=jsonObj.get("updatetime").toString();
                System.out.println("当前时间 "+updatetime);
                JSONArray trendArray = (JSONArray) jsonObj.get("trend");
                System.out.println("数据 "+trendArray);
                for (Object o : trendArray) {
                    StockRtInfo stockRtInfo = new StockRtInfo();
                    String trend = (String)o;
                    // 处理
                    String[] trendArr = trend.split(",");
                    String curTime = trendArr[0];
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date date = dateFormat.parse(curTime);
                    BigDecimal curPrice = new BigDecimal(trendArr[1]);
                    String tradeAccount = trendArr[2];
                    String tradeVolume = trendArr[3];
                    BigDecimal Volume = new BigDecimal(tradeVolume);

                    stockRtInfo.setId(idWorker.nextId()+"");
                    stockRtInfo.setStockCode(code);
                    stockRtInfo.setCurTime(date);
                    stockRtInfo.setStockName(name);
                    stockRtInfo.setOpenPrice(price);
                    stockRtInfo.setPreClosePrice(lastclosingprice);
                    stockRtInfo.setCurPrice(curPrice);
//                    stockRtInfo.setMinPrice();
//                    stockRtInfo.setMaxPrice();
                    stockRtInfo.setTradeAmount(tradeAccount);
                    stockRtInfo.setTradeVolume(Volume);
                    rtInfoList.add(stockRtInfo);
                    stockRtInfoMapper.insert(stockRtInfo);
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 拉取股票代码
     *
     * @throws ParseException
     */
    @Test
    public void test01() throws ParseException {
        List<String> codeList = new ArrayList<>();
        for (int i = 10; i <= 13; i++) {
            List<String> list = parseStockCode(i, 30);
            if (list != null && list.size() > 0) {
                codeList.addAll(list);
            }
        }
        System.out.println("=================");
        System.out.println(codeList);
        for (String s : codeList) {
            parseStockCodeData(s);
        }

    }

    public List<String> parseStockCode(int pagenum, int pagesize) throws ParseException {
        List<String> codeList = new ArrayList<>();
        String host = "https://jsapigpcx.market.alicloudapi.com";
        String path = "/stock/list";
        String method = "GET";
        String appcode = "d47e8d73a72045b8b61a86764d7728ed";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("classid", "1");
        // 当前页
        querys.put("pagenum", pagenum + "");
        // 每页显示条数
        querys.put("pagesize", pagesize + "");
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            String resultJson = EntityUtils.toString(response.getEntity());
            Map map = JSON.parseObject(resultJson, Map.class);
            Map map1 = JSON.parseObject(map.get("result").toString(), Map.class);
            JSONArray jsonArray = (JSONArray) map1.get("list");
            for (Object o : jsonArray) {
                JSONObject jsonObj = (JSONObject) o;
                String name = jsonObj.get("name").toString();
                String code = jsonObj.get("code").toString();
                System.out.println(name + " : " + code);
                codeList.add(code);
            }
            return codeList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Test
    public void asd(){
        stockTimerService.getStockSectorRtIndex();

    }
    @Test
    public void aaffds() throws ParseException {
        stockTimerService.insertBatch();
    }
    @Test
    public void adsasd(){
        stockTimerService.getStockRtIndex();
    }
    @Test
    public void adssdasd() throws ParseException {
        stockTimerService.gtOuterMarkInfo();
    }
    @Test
    public void gddfg(){
        stockTimerService.getRtcode("600660");
    }
}
